package com.zl.roomdesign.main.dynamic

import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.zl.core.MainApp
import com.zl.core.api.ServiceGenerator
import com.zl.core.base.ModeFragment
import com.zl.core.view.LinearItemDecoration
import com.zl.roomdesign.R
import com.zl.roomdesign.main.ImageEntity
import com.zl.roomdesign.main.MainApi
import com.zl.roomdesign.main.PreviewActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_dynamic.*

/**
 * Created by zhangli on 2018/5/6,13:52<br/>
 */
class DynamicFragment : ModeFragment() {

    private val api = ServiceGenerator.createRxService(MainApi::class.java)

    private lateinit var mAdapter: CompositionAdapter
    private val mList = mutableListOf<ImageEntity>()

    override fun layoutId() = R.layout.fragment_dynamic

    override fun initView(savedInstanceState: Bundle?) {

        mAdapter = CompositionAdapter(mList, {
            val intent = Intent(activity, PreviewActivity::class.java)
            intent.putExtra("imgUrl", MainApp.instance.getServerHost() + mList[it.adapterPosition].fileName)
            startActivity(intent)
        })
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = mAdapter
        recyclerView.addItemDecoration(LinearItemDecoration())

        swipeRefreshLayout.setOnRefreshListener {
            getData()
        }
    }

    override fun setListener() {
    }

    override fun observe() {
    }

    override fun afterView() {
        getData()
    }

    private fun getData() {
        mList.clear()
        api.getAll()
                .map {
                    if (it.code == 0) {
                        return@map it.data
                    } else {
                        throw RuntimeException("error")
                    }
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnTerminate {
                    swipeRefreshLayout.isRefreshing = false
                    mAdapter.notifyDataSetChanged()
                }
                .subscribe({
                    mList.addAll(it!!)
                }, {
                    showToast(it.message + "")
                })
    }
}